/*
 * @Author       : tfhappy
 * @Date         : 2020-07-07 00:48:41
 * @LastEditTime : 2020-07-10 00:48:44
 * @FilePath     : /giteecli/common/common.go
 * @Description  :
 */
package common

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"net/http"

	jsoniter "github.com/json-iterator/go"
)

var (
	// todo: 空值问题
	JSON = jsoniter.ConfigCompatibleWithStandardLibrary
)

type CommonError struct {
	Message          string `json:"message"`
	Err              string `json:"error"`
	ErrorDescription string `json:"error_description"`
}

func (e CommonError) Error() string {
	return fmt.Sprintf("error: %s, description: %s, messsage: %s", e.Err, e.ErrorDescription, e.Message)
}

func (e CommonError) IsNil() bool {
	return e.Err == "" && e.ErrorDescription == "" && e.Message == ""
}

func ParseJsonBody(data io.Reader, v interface{}) (err error) {
	var d []byte
	d, err = ioutil.ReadAll(data)
	if err != nil {
		return
	}
	err = json.Unmarshal(d, v)
	if err != nil {
		log.Printf("parse body: %s", string(d))
	}
	return
}

func JsonPost(tURL string, data interface{}) (*http.Response, error) {
	bs, err := json.Marshal(data)
	if err != nil {
		return nil, err
	}
	client := &http.Client{}
	req, err := http.NewRequest("POST", tURL, bytes.NewReader(bs))
	if err != nil {
		return nil, err
	}
	req.Header.Set("Content-Type", "application/json")
	return client.Do(req)
}

func PanicError(err error) {
	if err != nil {
		panic(err)
	}
}
